// 登录成功
import { post } from './http'

import { ElNotification } from 'element-plus'
import { configStore, useAsideMenuStore, useUserStore } from '@/stores'
const getTime = () => {
  const hour = new Date().getHours()
  if (hour >= 6 && hour < 12) {
    return '早上好'
  } else if (hour >= 12 && hour < 18) {
    return '下午好'
  } else {
    return '晚上好'
  }
}
function loginSuccess(callback?: Function) {
  const menuList = useAsideMenuStore()
  // console.log(22,menuList);
  ElNotification({
    title: getTime(),
    message: '欢迎回来',
    showClose: false, //是否显示关闭按钮
  })
  // 定义菜单数组
  menuList.setAsideMenu([
    {
      path: '/home',
      index: '1',
      title: '首页',
      icon: 'HomeFilled',
      iconColor: '#f0f0f0',
    },
    {
      path: '/datascreen',
      iconColor: '#f0f0f0',
      index: '2',
      title: '数据大屏',
      icon: 'Platform',
    },
    {
      path: '',
      iconColor: '#f0f0f0',
      index: '3',
      title: '权限管理',
      icon: 'Platform',
      children: [
        {
          path: '/home/user',
          iconColor: '#f0f0f0',
          index: '3-1',
          title: '用户管理',
          parentTitle: '权限管理',
          icon: 'Platform',
        },
        {
          path: '/home/role',
          iconColor: '#f0f0f0',
          parentTitle: '权限管理',
          index: '3-2',
          title: '角色管理',
          icon: 'Platform',
        },
        {
          path: '/home/permission',
          iconColor: '#f0f0f0',
          parentTitle: '权限管理',
          index: '3-3',
          title: '菜单管理',
          icon: 'Platform',
        },
      ],
    },
    {
      path: '',
      iconColor: '#f0f0f0',
      index: '4',
      title: '商品管理',
      icon: 'Platform',
      children: [
        {
          path: '/home/attr',
          iconColor: '#f0f0f0',
          index: '4-1',
          title: '属性管理',
          parentTitle: '商品管理',
          icon: 'Platform',
        },
        {
          path: '/home/spu',
          iconColor: '#f0f0f0',
          index: '4-2',
          title: 'spu管理',
          parentTitle: '商品管理',
          icon: 'Platform',
        },
        {
          path: '/home/trademark',
          iconColor: '#f0f0f0',
          index: '4-3',
          title: '品牌管理',
          parentTitle: '商品管理',
          icon: 'Platform',
        },
        {
          path: '/home/sku',
          iconColor: '#f0f0f0',
          index: '4-',
          title: 'sku管理',
          parentTitle: '商品管理',
          icon: 'Platform',
        },
      ],
    },
  ])
  // post("/asideMenu", {
  // },{}).then(res => {
  //   console.log(res)
  // })
}
//退出登录
let logOut = function (router: any, route: any) {
  // if (getClientName() == "app") {
  // 	//退出推送服务
  // 	endPushService();
  // 	//注册小鱼会议插件
  // 	if (dsf.config.login.registerXY) {
  // 		$XYLink.execute(["logout", {}], function (success) {
  // 			console.log(success)
  // 		}, function (error) {
  // 			console.log(error)
  // 		});
  // 	}
  // }
  // VuexStore.commit("changeAppFooter", [])//退出时清空底部菜单
  // VuexStore.dispatch("applications/setMyMenus", [])
  // VuexStore.dispatch("applications/setMenus", []) //退出时清空应用菜单
  // window.vueObj.$bus.emit('footerMenu');
  // window.vueObj.$bus.emit('clearCache');
  // removeSessionStore('user');
  // removeSessionStore('homePage');
  // removeSessionStore('loginToken');
  // removeSessionStore('imAccessToken');
  // removeToLocalStore('user');
  // removeToLocalStore('loginToken');
  // removeToLocalStore('userName');
  // removeToLocalStore('passWord');
  // removeToLocalStore('gesture_pas');
  // removeToLocalStore('autoLogin');
  // removeToLocalStore('mySetting');
  // removeToLocalStore('lastLoginType');
  // removeToLocalStore('TY_USER_ID'); // [赣政通]APM（第三方流量监控）用户ID
  // removeSessionStore("defaultcount");

  let logOutUrl = configStore().config.logOutUrl || '/login'
  router.replace({
    path: logOutUrl,
    query: {
      ...route.query,
    },
  })
}
let loadLocalStore = (name: string) => {
  try {
    const serializedState = localStorage.getItem(name)
    if (serializedState === null) {
      return undefined
    }
    return JSON.parse(serializedState)
  } catch (e) {
    return undefined
  }
}

let loadSessionStore = (name: string) => {
  try {
    const serializedState = sessionStorage.getItem(name)
    if (serializedState === null) {
      return undefined
    }
    return JSON.parse(serializedState)
  } catch (e) {
    return undefined
  }
}

let saveToLocalStore = (name: string, state: any) => {
  try {
    const serializedState = JSON.stringify(state)
    localStorage.setItem(name, serializedState)
  } catch (e) {
    //ignore errors
  }
}

let saveToSessionStore = (name: string, state: any) => {
  try {
    const serializedState = JSON.stringify(state)
    sessionStorage.setItem(name, serializedState)
  } catch (e) {
    //ignore errors
  }
}

let removeToLocalStore = (name: string) => {
  try {
    localStorage.removeItem(name)
  } catch (e) {
    //ignore errors
  }
}

let removeSessionStore = (name: string) => {
  try {
    sessionStorage.removeItem(name)
  } catch (e) {
    //ignore errors
  }
}

let clearSession = () => {
  sessionStorage.clear()
}

let clearLocalStore = () => {
  localStorage.clear()
}
//获取设备名称
let getClientName = () => {
  let consoleName = 'browser' //默认是浏览器模式，不在任何设备下，根据当前加载的壳userAgent判断使用设备
  if (window.navigator.userAgent.includes('mobileIM')) {
    consoleName = 'mobileIM'
  } else if (window.navigator.userAgent.toLowerCase().includes('micromessenger')) {
    consoleName = 'wechat'
    if (window.location.href.includes('digitalgd') || window.location.href.includes('gdzwfw'))
      consoleName = 'digitalgd'
  } else if (window.navigator.userAgent.toLowerCase().includes('taurusapp')) {
    consoleName = 'govding'
  } else if (
    window.navigator.userAgent.toLowerCase().includes('com.alibaba.android.rimet') ||
    window.navigator.userAgent.toLowerCase().includes('dingtalk')
  ) {
    consoleName = 'dingding'
  } else if (window.navigator.userAgent.toLowerCase().includes('caiyun')) {
    consoleName = 'xunmeng'
  } else if (window.navigator.userAgent.toLowerCase().includes('eshimin')) {
    consoleName = 'eshimin'
  } else if (window.navigator.userAgent.toLowerCase().includes('mpaasclient')) {
    consoleName = 'mpaas'
  }
  //console.log("consoleName",consoleName)
  return consoleName
}
//获取设备类型
let getClientType = () => {
  let consoleType = 'mobile'
  // var browser = {
  //   versions: function () {
  //     var u = navigator.userAgent,
  //       app = navigator.appVersion;
  //     return { //移动终端浏览器版本信息
  //       trident: u.indexOf("Trident") > -1, //IE内核
  //       presto: u.indexOf("Presto") > -1, //opera内核
  //       webKit: u.indexOf("AppleWebKit") > -1, //苹果、谷歌内核
  //       gecko: u.indexOf("Gecko") > -1 && u.indexOf("KHTML") == -1, //火狐内核
  //       mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
  //       ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
  //       android: u.indexOf("Android") > -1 || u.indexOf("Linux") > -1, //android终端或者uc浏览器
  //       iPhone: u.indexOf("iPhone") > -1, //是否为iPhone或者QQHD浏览器
  //       iPad: u.indexOf("iPad") > -1, //是否iPad
  //       webApp: u.indexOf("Safari") == -1 //是否web应该程序，没有头部与底部
  //     };
  //   }(),
  //   language: (navigator.browserLanguage || navigator.language).toLowerCase()
  // }
  // document.writeln(" 是否为移动终端: "+browser.versions.mobile);
  // document.writeln(" 是否iPad: "+browser.versions.iPad);
  let ua = navigator.userAgent,
    isAndroid = /(?:Android)/.test(ua),
    isFireFox = /(?:Firefox)/.test(ua)
  let isTablet =
    /(?:iPad|PlayBook)/.test(ua) ||
    (isAndroid && !/(?:Mobile)/.test(ua)) ||
    (isFireFox && /(?:Tablet)/.test(ua)) ||
    /(?:BRT-AN09)/.test(ua)

  if (isTablet) {
    consoleType = 'iPad'
  }
  if (
    !isTablet &&
    document.documentElement.clientWidth >= 600 &&
    document.documentElement.clientHeight >= 600
  ) {
    // 如果没判断出是pad，再进行屏幕宽高判断
    consoleType = 'iPad'
  }
  return consoleType
}
//替换url里面的[]动态参数，支持session、get参数、路由参数、dataObj属性
let getReplaceUrl = (url: string, dataObj?: any, routeParams?: any) => {
  let userData = loadSessionStore('user')
  if (typeof url === 'string') {
    let regex2 = /\[(.+?)\]/g // [] 中括号
    if (url.match(regex2)) {
      // 有匹配才替换[]中的参数
      url.match(regex2)?.forEach((element) => {
        let key = element.replace('[', '').replace(']', '')
        if (routeParams.params[key]) {
          url = url.replace(element, routeParams.params[key])
        }
        if (routeParams.query[key]) {
          url = url.replace(element, routeParams.query[key])
        }
        if (dataObj && dataObj[key]) {
          url = url.replace(element, dataObj[key])
        }
      })
    }
    if (userData) {
      return url
        .replace('[user_id]', userData.user_id)
        .replace('[userid]', userData.user_id)
        .replace('[name]', userData.name)
        .replace('[deptId]', userData.deptId)
        .replace('[deptName]', userData.deptName)
        .replace('[logName]', userData.logName)
        .replace('[mobile]', userData.mobile)
        .replace('[root_dept_id]', userData.root_dept_id)
        .replace('[unitId]', userData.unitId)
        .replace('[communityId]', userData.communityId)
        .replace('[access_token]', loadSessionStore('imAccessToken').access_token) //特殊处理IM的accesstoken
    }
  } else return url
}
let parseParamsToUrl = (data: any) => {
  //把json对象转成url文号参数
  try {
    var tempArr = []
    for (var i in data) {
      var key = encodeURIComponent(i)
      var value = encodeURIComponent(data[i])
      tempArr.push(key + '=' + value)
    }
    var urlParamsStr = tempArr.join('&')
    return urlParamsStr
  } catch (err) {
    return ''
  }
}
let getParamsFormUrl = (url: any) => {
  //根据URL文号参数获取JSON对象
  try {
    url = url.match(/\?([^#]+)/)[1] || ''
    const obj: { [key: string]: string } = {}
    const arr = url.split('&')
    for (let i = 0; i < arr.length; i++) {
      let subArr = arr[i].split('=')
      let key = decodeURIComponent(subArr[0])
      let value = decodeURIComponent(subArr[1])
      obj[key] = value
    }
    return obj
  } catch (err) {
    return null
  }
}
function deepClone(target: any) {
  // 处理null、undefined、原始数据类型（数字、字符串、布尔值等）
  if (target === null || typeof target !== 'object') {
    return target
  }
  // WeakMap作为记录对象Hash表（用于防止循环引用）
  const map = new WeakMap()

  // 判断是否为object类型的辅助函数，减少重复代码
  function isObject(target: any) {
    return (typeof target === 'object' && target) || typeof target === 'function'
  }

  function clone(data: any) {
    // 基础类型直接返回值
    if (!isObject(data)) {
      return data
    }

    // 日期或者正则对象则直接构造一个新的对象返回
    if ([Date, RegExp].includes(data.constructor)) {
      return new data.constructor(data)
    }

    // 处理函数对象
    if (typeof data === 'function') {
      return new Function('return ' + data.toString())()
    }

    // 如果该对象已存在，则直接返回该对象
    const exist = map.get(data)
    if (exist) {
      return exist
    }

    // 处理Map对象
    if (data instanceof Map) {
      const result = new Map()
      map.set(data, result)
      data.forEach((val, key) => {
        // 注意：map中的值为object的话也得深拷贝
        if (isObject(val)) {
          result.set(key, clone(val))
        } else {
          result.set(key, val)
        }
      })
      return result
    }

    // 处理Set对象
    if (data instanceof Set) {
      const result = new Set()
      map.set(data, result)
      data.forEach((val) => {
        // 注意：set中的值为object的话也得深拷贝
        if (isObject(val)) {
          result.add(clone(val))
        } else {
          result.add(val)
        }
      })
      return result
    }

    // 收集键名（考虑了以Symbol作为key以及不可枚举的属性）
    const keys = Reflect.ownKeys(data)
    // 利用 Object 的 getOwnPropertyDescriptors 方法可以获得对象的所有属性以及对应的属性描述
    const allDesc = Object.getOwnPropertyDescriptors(data)
    // 结合 Object 的 create 方法创建一个新对象，并继承传入原对象的原型链， 这里得到的result是对data的浅拷贝
    const result = Object.create(Object.getPrototypeOf(data), allDesc)

    // 新对象加入到map中，进行记录
    map.set(data, result)

    // Object.create()是浅拷贝，所以要判断并递归执行深拷贝
    keys.forEach((key) => {
      const val = data[key]
      if (isObject(val)) {
        // 属性值为 对象类型 或 函数对象 的话也需要进行深拷贝
        result[key] = clone(val)
      } else {
        result[key] = val
      }
    })
    return result
  }

  return clone(target)
}
function getCurrentFormattedTime(format = 'YYYY-MM-DD HH:mm:ss') {
  // 创建一个新的Date对象，表示当前时间
  const now = new Date()

  // 定义一个对象来映射格式字符串中的标记到Date对象的方法
  const formatMap: any = {
    YYYY: now.getFullYear(),
    MM: String(now.getMonth() + 1).padStart(2, '0'), // 月份从0开始，加1并填充0
    DD: String(now.getDate()).padStart(2, '0'), // 填充0
    HH: String(now.getHours()).padStart(2, '0'), // 填充0
    mm: String(now.getMinutes()).padStart(2, '0'), // 填充0
    ss: String(now.getSeconds()).padStart(2, '0'), // 填充0
  }

  // 使用正则表达式替换格式字符串中的标记为对应的值
  return format.replace(/YYYY|MM|DD|HH|mm|ss/g, (match) => formatMap[match])
}
export {
  deepClone,
  getParamsFormUrl,
  loadLocalStore,
  loginSuccess,
  saveToLocalStore,
  saveToSessionStore,
  loadSessionStore,
  removeSessionStore,
  removeToLocalStore,
  clearLocalStore,
  clearSession,
  getClientName,
  getClientType,
  getReplaceUrl,
  parseParamsToUrl,
  logOut,
  getCurrentFormattedTime,
}
